package cn.jcby.app.util;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author LHT
 * @date 2021-11-26
 */
public class IOUtil {
    public static void downloadJson(HttpServletResponse response, String fileName, String info) {

        try {
            String encodeName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());

            response.setCharacterEncoding("utf-8");
            /*  设置文件ContentType类型，这样设置，会自动判断下载文件类型   */
            response.setContentType("application/multipart/form-data");
            /* 设置文件头：最后一个参数是设置下载文件名   */
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");//设置允许跨域的key
            response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + encodeName +".json");

            /* 用流将数据写给前端 */
            OutputStream os = response.getOutputStream();
            os.write(info.getBytes());
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 浏览器下载文件
     * @param file
     * @param response
     */
    public static void downloadFile(File file, HttpServletResponse response) {
        InputStream fin = null;
        ServletOutputStream out = null;
        try {
            String fileName = file.getName();
            String encodeName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());

            fin = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(fin);
            out = response.getOutputStream();
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/force-download");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");//设置允许跨域的key
            response.setHeader("Content-Disposition", "attachment;filename=" + encodeName);

            byte[] buffer = new byte[1024];
            int i = bis.read(buffer);
            while (i != -1) {
                out.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            out.flush();
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(fin != null) {fin.close();}
                if(out != null) {out.close();}
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
